const ol = window.ol
const vectorLayerMap = {}

/**
 * * 把要素追加到矢量图层
 * @param layerId {String}
 * @param features {Array<ol.source.Vector>} 要素集合
 * @returns {ol.layer.Vector}
 */
function createVectorLayer(layerId, features) {
  let vectorLayer = getLayerById(layerId)
  if (!vectorLayer) {
    // 矢量标注的数据源
    const vectorSource = new ol.source.Vector({
      features: features
    })
    vectorLayer = new ol.layer.Vector({
      source: vectorSource
    })
    setLayerById(layerId, vectorLayer)
  } else {
    vectorLayer.getSource().addFeatures(features)
  }
  return vectorLayer
}

/**
 * 缓存vectorLayer
 * @param layerId {String}
 * @param vectorLayer
 */
function setLayerById(layerId, vectorLayer) {
  vectorLayerMap[layerId] = vectorLayer
}

/**
 * 移除图层
 * @param layerId {String}
 * @param map
 */
function removeLayer(layerId, map) {
  const vectorLayer = getLayerById(layerId)
  if (vectorLayer) {
    map.removeLayer(vectorLayer)
    delete vectorLayerMap[layerId]
  }
}
/**
 * 根据id获取图层对象
 * @param layerId {String}
 * @returns {*}
 */
function getLayerById(layerId) {
  return vectorLayerMap[layerId]
}

/**
 * 是否存在layer对象
 * @param layerId {String}
 * @returns {boolean}
 */
function hasLayerById(layerId) {
  return getLayerById(layerId) !== undefined
}

/**
 * 显示或者隐藏图层
 * @param layerId {String}
 * @param visible
 */
function setLayerVisble(layerId, visible) {
  const vectorLayer = getLayerById(layerId)
  if (vectorLayer) {
    vectorLayer.setVisible(visible)
  }
}

export { createVectorLayer, setLayerById, removeLayer, getLayerById, hasLayerById, setLayerVisble }
